//
//  SCAppVersionJudgment.m
//  SCFoundationKit
//
//  Created by Chao Sheng on 2023/10/16.
//

#import "SCAppVersionJudgment.h"
#import "SCNetRequest.h"
#import "SCBasicKit.h"

@implementation SCAppVersionJudgment
/// #define StudentAddress @"https://itunes.apple.com/lookup?id=1454379239"

- (void)judgeLocalVersionWithAPPStoreVersion:(NSString *)appStoreUrl NetWorkVersion:(NSString *)netWorkurl completion:(void (^)(SCAppVersionType, id _Nonnull))completion {
    
    __weak typeof(self) weakSelf = self;
    [SCNetRequest.share.url(netWorkurl).method(SCNetRequestHttpMethod_POST) startRequestWithResponse:^(id  _Nonnull response, NSError * _Nonnull error) {
        if(error) {
            return;
        }
        /// 获取当前应用的数据
        NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
        NSArray *systemList = response[@"systemConfig"];
        __block NSDictionary *systemConfig;
        [systemList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if([obj[@"system"] isEqual:appName]) {
                systemConfig = obj;
            }
        }];
        if([systemConfig sc_isEmpty]) {
            return;
        }
        
        NSInteger systemState = ((NSNumber*)systemConfig[@"systemState"]).integerValue;
        NSString *message = systemConfig[@"systemInfo"];
        
        if (systemState == 0) { // 即将维护
            
            completion(SCAppVersionTypeMessage,message);
            
        } else if (systemState == 1) { //正在维护
            
            completion(SCAppVersionTypeMessageWithUnUsed,message);

        } else { //请求商店数据信息，判断
            [weakSelf requestAppstoreVersion:appStoreUrl NetWorkVersion:systemConfig completion:^(SCAppVersionType type, id _Nonnull message) {
                completion(SCAppVersionTypeMessageWithUnUsed,message);
            }];
        }
        
    }];
}

- (void)requestAppstoreVersion:(NSString*)appStoreUrl NetWorkVersion:(NSDictionary *)netWorkDic completion:(void (^)(SCAppVersionType, id _Nonnull))completion {
    
    NSString *netWorkVersion = netWorkDic[@"version"];
    NSString *localVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    /// 版本号按四位来处理判断，比如1.0，转换成 四位数字就是 1000， 1.0.11 转换成 四位数字就是 1011, 不足四位，自动补零
    __weak typeof(self) weakSelf = self;
    [SCNetRequest.share.url(appStoreUrl).method(SCNetRequestHttpMethod_POST) startRequestWithResponse:^(id  _Nonnull response, NSError * _Nonnull error) {
        NSString *appstoreVersion = [response[@"results"] lastObject][@"version"];
        NSString *message = [response[@"results"] lastObject][@"releaseNotes"];
        
        NSInteger netWorkVersionNum = [weakSelf transformVersionToNum:netWorkVersion];
        NSInteger localVersionNum = [weakSelf transformVersionToNum:localVersion];
        NSInteger appstoreVersionNum = [weakSelf transformVersionToNum:appstoreVersion];
        
        if (localVersionNum > appstoreVersionNum) { // 本地大于商店，表明是开发版本，不提示更新
            NSLog(@"本地大于商店版本，表明是开发版本，不提示更新");
            completion(SCAppVersionTypeDefault,message);

        } else if (localVersionNum < netWorkVersionNum) { //本地版本小于 网络设置的版本号（网络设置的版本号，表示要强制更新的版号）
            NSLog(@"本地版本小于网络设置的版本号，强制更新");
            completion(SCAppVersionTypeForceUpdate,message);

        } else if (localVersionNum < appstoreVersionNum) {
            NSLog(@"本地版本小于商店的版本号，提示更新");
            completion(SCAppVersionTypeUpdate,message);
        }
        
    }];
}

- (NSInteger )transformVersionToNum:(NSString*)version {
    version = [version stringByReplacingOccurrencesOfString:@"." withString:@""];
    NSInteger zeroCount = 4 - version.length;
    for(NSInteger i = 0; i < zeroCount; i++) {
        version = [version stringByAppendingString:@"0"];
    }
    return version.integerValue;
}

@end
